import * as Cesium from '@cesium/Source/Cesium.js';


function toDMS(deg) {
  const d = Math.floor(deg);
  const m = Math.abs(deg - d) * 60;
  var mm = Math.floor(m);
  var ss = ((m - mm) * 60).toFixed(2);
  if (10 > ss) {
    ss = "0" + ss
  }
  if (10 > m) {
    mm = "0" + mm
  }
  return `${d}°${mm}′${ss}″`
}

//线长度测量
export default function measureLine(viewer, callback) {

  // let nowCartesian3,nowCartographic,nowWgs84;

  function nowCartographic(nowCartesian3) {
    // https://blog.csdn.net/Feelings_/article/details/99441700
    if (!viewer) return {};
    var ellipsoid = viewer.scene.globe.ellipsoid;
    var cartographic = ellipsoid.cartesianToCartographic(nowCartesian3);
    return cartographic;
  }

  function nowWgs84(nowCartographic) {
    // https://blog.csdn.net/Feelings_/article/details/99441700
    if (!viewer) return {};
    var lat = Cesium.Math.toDegrees(nowCartographic.latitude);
    var lon = Cesium.Math.toDegrees(nowCartographic.longitude);
    var alt = viewer.scene.globe.getHeight(nowCartographic);
    return {
      lat,
      lon,
      alt
    };
  }

  function strWgs84(nowCartographic) {
    // https://blog.csdn.net/Feelings_/article/details/99441700
    if (!viewer) return {};
    var lat = toDMS(Cesium.Math.toDegrees(nowCartographic.latitude));
    var lon = toDMS(Cesium.Math.toDegrees(nowCartographic.longitude));
    var alt = viewer.scene.globe.getHeight(nowCartographic)||0;
    alt = alt.toFixed(2);
    return {
      lat,
      lon,
      alt
    };
  }

  function handleMouseMove(event) {
    var wp = event.endPosition;
    if (!Cesium.defined(wp)) {
      return
    }
    var ray = viewer.scene.camera.getPickRay(wp);
    if (!Cesium.defined(ray)) {
      return
    }
    var cartesian3 = viewer.scene.globe.pick(ray, viewer.scene);
    if (!Cesium.defined(cartesian3)) {
      return
    }
    if (cartesian3) {
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
      // var lon = Cesium.Math.toDegrees(cartographic.longitude);
      // var lat = Cesium.Math.toDegrees(cartographic.latitude);
      const wgs84 = strWgs84(cartographic);
      wgs84.alt = viewer.scene.globe.getHeight(cartographic);
      callback && callback({
        cartesian3,
        cartographic,
        wgs84
      })
    }
  }

  function onMouseMove(event) {
    var newPosition = viewer.scene.pickPosition(event.endPosition);
    if(!newPosition) return;
    const cartesian3 = newPosition;
    const cartographic = nowCartographic(newPosition);
    const wgs84 = nowWgs84(cartographic);
    const dms = strWgs84(cartographic);
    callback && callback({
      cartesian3,
      cartographic,
      wgs84,
      dms
    })
  }

  var handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
  //鼠标移动
  handler.setInputAction(onMouseMove, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}
